/*-----------------------------------------------------------------------------
	The contents of this file are subject to the Mozilla Public License
	Version 1.1 (the "License"); you may not use this file except in
	compliance with the License. You may obtain a copy of the License at
	http://www.mozilla.org/MPL/
	
	Software distributed under the License is distributed on an "AS IS"
	basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
	License for the specific language governing rights and limitations
	under the License.
	
	The Original Code is Fever Framework code.
	
	The Initial Developer of the Original Code is Romain Ecarnot.
	Portions created by Initial Developer are Copyright (C) 2006
	the Initial Developer. All Rights Reserved.
	
	Contributor(s):
	
	Unless required by applicable law or agreed to in writing, software
	distributed under the License is distributed on an "AS IS" BASIS,
	WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
	See the License for the specific language governing permissions and
	limitations under the License.
-----------------------------------------------------------------------------*/

import org.aswing.ASColor;
import org.aswing.ASWingUtils;
import org.aswing.geom.Point;
import org.aswing.JButton;
import org.aswing.JColorChooser;
import org.aswing.JFrame;
import org.aswing.MouseManager;

import com.bourre.core.IAccessor;
import com.bourre.utils.ClassUtils;

import fever.app.accelerator.Keyboard;
import fever.app.accelerator.ShortcutLocator;
import fever.app.accelerator.ShortcutMap;
import fever.display.ModalScreen;
import fever.medias.sound.AppSoundFactory;

import flash.display.BitmapData;

import fvaswing.components.colorchooser.FvColorChooserResources;
import fvaswing.components.colorchooser.FvColorChooserUI;
import fvaswing.components.colorchooser.FvColorPickerCursor;
import fvaswing.components.FvButton;
import fvaswing.components.FvUIBuffer;

/**
 * Color chooser component dialog.
 *
 * @author Romain Ecarnot
 */
class fvaswing.components.FvColorChooser extends JColorChooser implements FvUIBuffer
{
	//-------------------------------------------------------------------------
	// Private properties
	//-------------------------------------------------------------------------
	
	private static var _instance : FvColorChooser;
	
	private var _modal : ModalScreen;
	private var _modalTarget : MovieClip;
	private var _frame : JFrame;
	private var _pickerButton : JButton;
	private var _canPick : Boolean;
	private var _accessor : IAccessor;
	private var _connectAdjust : Boolean;	private var _connectChange : Boolean;
	private var _storedColor : ASColor;
	private var _keyMap : ShortcutMap;
	
	// overrides
	private var okButton : FvButton;
	private var cancelButton : FvButton;
	
	
	//-------------------------------------------------------------------------
	// Public API
	//-------------------------------------------------------------------------
	
	/**
	 * Returns {@link FvColorChooser} instance.
	 * 
	 * <p>Always returns the same instance.<br />
	 * Design Pattern Singleton.
	 * @return {@link FvColorChooser} instance
	 */
	public static function getInstance() : FvColorChooser
	{
		if( !_instance ) _instance = new FvColorChooser();
		return _instance;	
	}
	
	/**
	 * Returns the picker button instance.
	 */
	public function getPickerButton() : JButton
	{
		if( !_pickerButton ) 
		{
			_pickerButton = new JButton( FvColorChooserResources.getInstance().pickerLabel );
			_pickerButton.addActionListener( _pickColor, this );
		}
		return _pickerButton;
	}
	
	/**
	 * Opens dialog.
	 */
	public function open() : Void
	{
		_keyMap.load();
		
		_updateLocalisation();
		
		_storedColor = ( _accessor )
			? _accessor.getValue()
			: getSelectedColor(); 
		
		setSelectedColor( _storedColor );
		
		_layout();
		
		_modal.hide();
		
		_frame.show();
	}
	
	/**
	 * Force close.
	 */
	public function close() : Void
	{
		_handleCancel();	
	}
	
	/**
	 * Connects <strong>Pixlib Accessor</strong> to selector.
	 *
	 * <p>When chooser is closed, result is automatically sent to accessor instance.
	 * 
	 * <p>Example
	 * {@code
	 *   var input : JTextField = new JTextField( "", 15 );
	 *   chooser.connect( AccessorFactory.getInstance( input, input.setText, input.getText ) );
	 *   chooser.open();
	 * }
	 * 
	 * @param accessor IAccessor instance ( take a look at Pixlib bourre.core package )
	 * @param listenAdjustement Indicates if result is passed only when color change ( default 
	 * behaviour == {@code false} or {@code undefined}, or if accessor listen the color 
	 * change <strong>and</strong> adjustement too {@code true}
	 */
	public function connect( accessor : IAccessor, listenAdjustement : Boolean, listenChange : Boolean ) : Void
	{
		_accessor = accessor;
		_connectAdjust = ( listenAdjustement ) ? true : false;		_connectChange = ( listenChange ) ? true : false;
	}
	
	/**
	 * Releases accessor connection.
	 */
	public function disconnect() : Void
	{
		_accessor = null;
	}
	
	public function getUI() : FvColorChooserUI
	{
		return FvColorChooserUI( ui );
	}
	
	/**
     * Resets the UI property to a value from the current look and feel.
     */ 
	public function updateUI() : Void
	{
		setUI( FvColorChooserUI.getInstance() );
	}
	
	/**
     * Returns the <code>UIDefaults</code> key used to
     * look up the name of the <code>org.aswing.plaf.ComponentUI</code>
     * class that defines the look and feel
     * for this component.
     */ 
	public function getUIClassID() : String
	{
		return 'FvColorChooserUI';
	}
	
	/**
	 * Returns the ok button to finish the choosing.
	 */
	public function getOkButton() : FvButton
	{
		return okButton;
	}
	
	/**
	 * Returns the cancel button which use to cancel the choosing.
	 */
	public function getCancelButton() : FvButton
	{
		return cancelButton;
	}
	
	/**
	 * Insert component into buffer
	 */
	public function preload() : Void
	{
		_frame.setLocation( 4000, 3000 );
		_frame.show();	
	}
	
	
	//-------------------------------------------------------------------------
	// Private implementation
	//-------------------------------------------------------------------------
	
	private static function createDialog() : Void {}	private static function showDialog() : Void {}
	
	/**
	 * Constructor.
	 */
	private function FvColorChooser()
	{
		_canPick = false;
		
		_keyMap = ShortcutLocator.getMap( ClassUtils.getFullyQualifiedClassName( this ) );
		_keyMap.registerEvent( Keyboard.onKeyESCAPE, this, _closeDialog );
		
		okButton = _createButton( FvColorChooserResources.getInstance().okLabel );
		cancelButton = _createButton( FvColorChooserResources.getInstance().cancelLabel );
		
		_configureUI();
		_configureListeners();
	}
	
	private function _configureUI() : Void
	{
		setUI( FvColorChooserUI.getInstance() );
		
		getOkButton().addActionListener( _handleResult, this );
		getCancelButton().addActionListener( _handleCancel, this );
		
		_frame = new JFrame( _getModalTarget(), "", false );
		_frame.setContentPane( this );
		_frame.setResizable( false );
		_frame.setClosable( false );
		_frame.setSize( 350, 265 );
		_frame.addEventListener( JFrame.ON_WINDOW_CLOSING,_handleResult, this );
	}
	
	private function _getModalTarget() : MovieClip
	{
		_modal.dispose();
		_modal = new ModalScreen( 0xffffff, 0 );
		_modal.enableScreenshot = true;
		_modalTarget = _modal.getModalTarget();
		
		return _modalTarget;
	}
	
	private function _createButton( caption : String ) : FvButton
	{
		var b : FvButton = new FvButton( caption );
		b.setShortcut( null, _keyMap.getName() );
		
		if( AppSoundFactory.getSoundFactory().hasSound( FvButton.DEFAULT_CLICK_SOUND ) )
		{
			b.setSoundID( FvButton.DEFAULT_CLICK_SOUND );
		}
		
		return b;
	}
	
	private function _configureListeners() : Void
	{
		_connectAdjust = false;
		_connectChange = false;
		
		addColorAdjustingListener( _handleColorAdjusted, this );			addChangeListener( _handleColorChanged, this );
	}
	
	private function _updateLocalisation() : Void
	{
		getOkButton().setText( FvColorChooserResources.getInstance().okLabel );
		getCancelButton().setText( FvColorChooserResources.getInstance().cancelLabel );
		getPickerButton().setText( FvColorChooserResources.getInstance().pickerLabel );
		
		_frame.setTitle( FvColorChooserResources.getInstance().title );
	}
	
	private function _layout() : Void
	{
		var location : Point = ASWingUtils.getScreenCenterPosition();
		location.x -= _frame.getWidth()/2;
		location.y -= _frame.getHeight()/2;
		_frame.setLocation( location );
	}
	
	private function _handleResult( ) : Void
	{
		_fireNewColor( getSelectedColor() );
	}
	
	private function _handleCancel() : Void
	{
		_fireNewColor( _storedColor );
	}
	
	private function _closeDialog() : Void
	{
		_keyMap.unload();
		_modal.hide();
		_frame.tryToClose();	
	}
	
	private function _pickColor() : Void
	{
		_fireNewColor( _storedColor );
		
		_modal.show();
		_frame.hide();
		
		FvColorPickerCursor.show();
		_canPick = true;
		MouseManager.addEventListener( MouseManager.ON_MOUSE_UP, _checkPickedColor, this);
	}
	
	private function _checkPickedColor( manager : MouseManager ) : Void
	{
		if( _canPick )
		{
			_canPick = false;
			FvColorPickerCursor.hide();
			MouseManager.removeEventListener( this );
			
			var bmp : BitmapData = _modal.getScreenShot().getData();
			var color : Number = bmp.getPixel( _modalTarget._xmouse, _modalTarget._ymouse );
			
			setSelectedColor( new ASColor( color, 100 ) );
			_modal.hide();
			_frame.show();
		}
	}
	
	private function _fireNewColor( color : ASColor ) : Void
	{
		_accessor.setValue( color );
		_closeDialog();
	}
	
	private function _handleColorAdjusted() : Void
	{
		if( _connectAdjust ) _accessor.setValue( getSelectedColor() );
	}
	
	private function _handleColorChanged() : Void
	{
		if( _connectChange ) _accessor.setValue( getSelectedColor() );
	}
	
}